package conf

import (
	"encoding/json"
	"fmt"
	"os"
)

const (
	defConfigFile = "/etc/pac/config.json"
)

const DBAvailable = true

// LogConf 日志配置信息
type LogConf struct {
	ConfFile string `json:"confFile"`
}

// DbConf 数据库配置信息
type DbConf struct {
	DataSourceName string `json:"dataSourceName"`
}

// SrvAddrConf 服务网络绑定、监听配置信息
type SrvAddrConf struct {
	Bind string `json:"bind"`
	Port int    `json:"port"`
}

// DeviceModbusMasterConf 设备配置
type DeviceModbusMasterConf struct {
	DevPath  string `json:"devPath"`
	BaudRate int    `json:"baudRate"`
	DataBits int    `json:"dataBits"`
	StopBits int    `json:"stopBits"`
	Parity   string `json:"parity"`
	SlaveId  int    `json:"slaveId"`
}

// AMapKeysConf 高德地图的 Key
type AMapKeysConf struct {
	Lbs               string `json:"lbs"`
	WebService        string `json:"webService"`
	WebServicePrivate string `json:"webServicePrivate,omitempty"`
}

// ProgramConf 程序配置信息
type ProgramConf struct {
	Log                LogConf                `json:"logConf"`
	DB                 DbConf                 `json:"db"`
	DeviceSrv          SrvAddrConf            `json:"deviceServer"`
	DeviceModbusSrv    SrvAddrConf            `json:"deviceModbusServer"`
	UserSrv            SrvAddrConf            `json:"userServer"`
	DeviceModbusMaster DeviceModbusMasterConf `json:"deviceModbusMaster"`
	AMapKeys           AMapKeysConf           `json:"AMapKeys"`
}

var (
	// Conf 程序配置信息
	Conf = ProgramConf{}
	// Log 日志配置信息
	Log *LogConf
	// DB 主机间通信模块配置信息
	DB *DbConf
	// DeviceSrv 设备服务网络绑定、监听配置信息
	DeviceSrv *SrvAddrConf
	// DeviceModbusSrv 设备 Modbus 服务网络绑定、监听配置信息
	DeviceModbusSrv *SrvAddrConf
	// UserSrv 用户服务网络绑定、监听配置信息
	UserSrv *SrvAddrConf
	// DeviceModbusMaster 设备 Modbus
	DeviceModbusMaster *DeviceModbusMasterConf
	// AMapKeys 高德地图的 Key
	AMapKeys *AMapKeysConf
)

// InitConf 初始化配置
func InitConf(filename string) error {
	if len(filename) == 0 {
		filename = defConfigFile
	}

	configFile, err := os.Open(filename)
	if err != nil {
		return fmt.Errorf("opening config file: %v", err)
	}

	jsonParser := json.NewDecoder(configFile)
	if err = jsonParser.Decode(&Conf); err != nil {
		return fmt.Errorf("parsing config file(%v): %v", filename, err)
	}

	return nil
}

func init() {
	Log = &Conf.Log
	DB = &Conf.DB
	DeviceSrv = &Conf.DeviceSrv
	DeviceModbusSrv = &Conf.DeviceModbusSrv
	UserSrv = &Conf.UserSrv
	DeviceModbusMaster = &Conf.DeviceModbusMaster
	AMapKeys = &Conf.AMapKeys
}
